//
//  SettingViewController.m
//  KurtulusLaw
//
//  Created by phuc phuc on 12/2/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "SettingViewController.h"
#import "PasscodeViewController.h"
#import "Terms.h"
#import "PrivacyView.h"
#import "PasscodeViewController.h"
#import "LoginViewController.h"
#import "ManagePasscode.h"
#import "CCommon.h"
#import "UIFacebookInvitation.h"
#import <Twitter/Twitter.h>
#import "KChangePasswordViewController.h"
#import "Constant.h"
#import <FacebookSDK/FacebookSDK.h>
@implementation SettingViewController
@synthesize tableViewSetting;


#pragma mark - UITableViewDataSource,UITableViewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return section == 0 ? 7 : 4;
}
-(NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
	return section == 0 ? NSLocalizedString(@"Settings", nil) : NSLocalizedString(@"Invite your friends to \nKurtulus & Partners", nil);
}


-(void)switchRememberPass : (id) sender
{
	UISwitch *_switch = (UISwitch*)sender;
	NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
	
	if (_switch.isOn) {
		NSLog(@"remember");
		NSString *strUserName = [CCommon shareUsername];
		NSString *strPassword = [CCommon sharePassword];
		[userDefault setObject: strUserName forKey: kKEY_USERNAME];
		[userDefault setObject: strPassword forKey: kKEY_PASSWORD];
		[userDefault synchronize];
	}
	else
	{
		[userDefault removeObjectForKey: kKEY_USERNAME];
		[userDefault removeObjectForKey: kKEY_PASSWORD];
		[userDefault synchronize];
	}
}

-(BOOL)checkRemember
{
	NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
	NSString *user = [userDefault objectForKey: kKEY_USERNAME];
	NSString *pass = [userDefault objectForKey: kKEY_PASSWORD];
	if ([user length] != 0 && [pass length] != 0) {
		return YES;
	}
	else
		return NO;
}
-(UITableViewCell*) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"Cell";
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    if (indexPath.section == 0) {
        switch (indexPath.row) {
            case 0:
            {
                cell.textLabel.text = NSLocalizedString(@"Remember Password", nil);
                UISwitch *switchPass = [[UISwitch alloc] initWithFrame:CGRectMake(208, 9, 20, 20)];
				if ([self checkRemember]) {
					[switchPass setOn:YES];
				}
				else
					[switchPass setOn:NO];
				
				[switchPass addTarget:self action:@selector(switchRememberPass:) forControlEvents:UIControlEventValueChanged];
                cell.accessoryType = UITableViewCellAccessoryNone;
                [cell.contentView addSubview:switchPass];
                break;
            }
            case 1:
            {
                cell.textLabel.text = NSLocalizedString(@"Passcode Lock", nil);
                UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(245, 12, 50, 20)];
                label.backgroundColor = [UIColor clearColor];
                label.font = [UIFont boldSystemFontOfSize:14.0f];
                label.textColor = [UIColor grayColor];
                if ([CCommon checkPasscode]) {
                    label.text = @"ON";
                }
                else
                    label.text = @"OFF";
                [cell.contentView addSubview:label];
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                break;
            }
			case 2:
			{
				cell.textLabel.text = NSLocalizedString(@"Change Password", nil);
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
				break;
			}
            case 3:
                cell.textLabel.text = NSLocalizedString(@"Terms and Conditions", nil);
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                break;
            case 4:
                cell.textLabel.text = NSLocalizedString(@"Privacy", nil);
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                break;
            case 5:
            {
                cell.textLabel.text = NSLocalizedString(@"Check for updates", nil);
                UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(240, 12, 50, 20)];
                label.font = [UIFont boldSystemFontOfSize:14.0f];
                label.textColor = [UIColor grayColor];
                label.backgroundColor = [UIColor clearColor];
				label.textAlignment = UITextAlignmentRight;
                label. text =[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
                [cell.contentView addSubview:label];
                cell.accessoryType = UITableViewCellAccessoryNone;
                break;
            }
            case 6:
                cell.textLabel.text = NSLocalizedString(@"Support", nil);
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                break;
                
            default:
                break;
        }
    }
    else
    {
        switch (indexPath.row) {
            case 0:
            {
                cell.textLabel.text = NSLocalizedString(@"Invite by Facebook", nil);
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                break;
            }
            case 1:
                cell.textLabel.text = NSLocalizedString(@"Invite by Twitter", nil);
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                break;
            case 2:
                cell.textLabel.text = NSLocalizedString(@"Invite by Mail", nil);
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                break;
			case 3:
                cell.textLabel.text = NSLocalizedString(@"Invite by SMS", nil);
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                break;
            default:
                break;
        }
    }
    
    return cell;
}

-(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    cell.selectionStyle = UITableViewCellSelectionStyleGray;
    cell.textLabel.textColor = [UIColor grayColor];
    cell.textLabel.font = [UIFont boldSystemFontOfSize:13.0f];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

-(void)back: (id)sender
{
    [self dismissModalViewControllerAnimated:YES];
}


-(void)logout : (id)sender
{
	[CCommon resetDataWhenLogout];
    LoginViewController *login = [[LoginViewController alloc] init];
    [login setModalTransitionStyle:UIModalTransitionStyleFlipHorizontal];
	
	UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:login];		
    [self presentModalViewController:nav animated:YES];
    
}
-(void) pushToTerms : (id) sender
{
    Terms *terms = [[Terms alloc] init];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:terms];
    [self presentModalViewController:nav animated:YES];
    
}
-(void) pushToPrivacy : (id) sender
{
    PrivacyView *privacy = [[PrivacyView alloc] init];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:privacy];
    [self presentModalViewController:nav animated:YES];
}

- (void)loginedFBFail {
    UIAlertView *alertView = [[UIAlertView alloc]
                              initWithTitle: NSLocalizedString(@"Message", nil)
                              message:@"Facebook login failed"
                              delegate:nil
                              cancelButtonTitle:@"OK"
                              otherButtonTitles:nil];
    [alertView show];
    
}

-(void)pushToFacebook
{
    [[FBSession activeSession] close];
    
    [FBSession openActiveSessionWithPermissions:[[NSMutableArray alloc] initWithObjects:@"publish_actions", @"publish_stream", nil]  allowLoginUI:YES completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
        switch (status) {
            case FBSessionStateOpen: {
                
                [self publishStory];
            }
                break;
            case FBSessionStateClosed:
            case FBSessionStateClosedLoginFailed:{
                // Once the user has logged in, we want them to 
                // be looking at the root view.
                [self loginedFBFail];
            }
                break;
            default:
                break;
                
        }
        if (error) {
            UIAlertView *alertView = [[UIAlertView alloc]
                                      initWithTitle:@"Error"
                                      message:error.localizedDescription
                                      delegate:nil
                                      cancelButtonTitle:@"OK"
                                      otherButtonTitles:nil];
            [alertView show];
        }  
    }];

}

- (void) pushToTwitter
{
//    WTwitterViewController *twitter = [[WTwitterViewController alloc] init];
//    [self presentModalViewController:twitter animated:YES];
    TWTweetComposeViewController *twitter = [[TWTweetComposeViewController alloc] init];
   
    NSString *text =  NSLocalizedString(@"www.kurtuluspartners.com\nModern Turkish Law Firm, I can follow my cases even from their mobile application. \nDefinitely Recommended!!!", nil);
    
    if ([text length] >= 140) {
        text = [text substringToIndex:139];
    }
        
    [twitter setInitialText:text];
    
      [self presentViewController:twitter animated:YES completion:nil];
    
    
    twitter.completionHandler = ^(TWTweetComposeViewControllerResult res) {
        
        if(res == TWTweetComposeViewControllerResultDone) {
            
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:NSLocalizedString(@"Message", <#comment#>) message:@"The tweet was posted successfully." delegate:self cancelButtonTitle: NSLocalizedString(@"OK", nil) otherButtonTitles: nil];
            
            [alert show];    
            
        }
        if(res == TWTweetComposeViewControllerResultCancelled) {
//            
//            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Cancelled" message:@"You Cancelled posting the Tweet." delegate:self cancelButtonTitle:@"Dismiss" otherButtonTitles: nil];
//            
//            [alert show];    
            
        }
        [self dismissModalViewControllerAnimated:YES];
        
    };

}

-(void) pushToMailSupport : (id) sender
{
    MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
    picker.mailComposeDelegate = self;
    [picker setSubject:@"Kurtulus & Partners"];
    // Set up recipients

    NSArray *toRecipients = [NSArray arrayWithObject: kMailSupportKurtulus];
    NSArray *toCC = [NSArray arrayWithObject:@"hasankurtulus@gmail.com"];
    NSString *emailBody = NSLocalizedString(@"How may we help you? Please explain in details\nPlease give us your contact details;\nName & Surname :\nCompany Name  :\nTelephone      :\nSkype          :", nil);
    [picker setToRecipients:toRecipients];
    [picker setCcRecipients:toCC];
    [picker setMessageBody:emailBody isHTML:NO];
    [self presentModalViewController:picker animated:YES];
}

-(void) pushToMailInvite : (id) sender
{
    MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
    picker.mailComposeDelegate = self;
    [picker setSubject:@"Kurtulus & Partners"];
    // Set up recipients
    
    NSArray *toRecipients = [NSArray arrayWithObject:@"kurtuluspartners.com"];
    NSString *emailBody = NSLocalizedString(@"www.kurtuluspartners.com\nModern Turkish Law Firm, I can follow my cases even from their mobile application. \nDefinitely Recommended!!!", nil);
    [picker setToRecipients:toRecipients];
    [picker setMessageBody:emailBody isHTML:NO];
    [self presentModalViewController:picker animated:YES];
}
- (void)sendSMS:(NSString *)bodyOfMessage recipientList:(NSArray *)recipients
{
    MFMessageComposeViewController *controller = [[MFMessageComposeViewController alloc] init] ;
    if([MFMessageComposeViewController canSendText])
    {
        controller.body = bodyOfMessage;    
        controller.recipients = recipients;
        controller.messageComposeDelegate = self;
        [self presentModalViewController:controller animated:YES];
    }    
}

- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
    [self dismissModalViewControllerAnimated:YES];
    
    if (result == MessageComposeResultCancelled)
        NSLog(@"Message cancelled");
    else if (result == MessageComposeResultSent)
        NSLog(@"Message sent");  
    else 
        NSLog(@"Message failed");
}
- (void)pushToChangePass:(id)sender {
	KChangePasswordViewController *changePass = [[KChangePasswordViewController alloc] initWithNibName:@"KChangePasswordViewController" bundle:[NSBundle mainBundle]];
	UINavigationController *nav  = [[UINavigationController alloc] initWithRootViewController:changePass];
    [self presentModalViewController:nav animated:YES];
}

-(void)pushToPasscode : (id) sender
{
    PasscodeViewController *passCode = [[PasscodeViewController alloc] init];
    UINavigationController *nav  = [[UINavigationController alloc] initWithRootViewController:passCode];
    [self presentModalViewController:nav animated:YES];
    
}
-(void)pushToManagePasscode : (id) sender
{
    ManagePasscode *passCode = [[ManagePasscode alloc] init];
    UINavigationController *nav  = [[UINavigationController alloc] initWithRootViewController:passCode];
    [self presentModalViewController:nav animated:YES];
    
}
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error
{
    // Notifies users about errors associated with the interface
    switch (result)
    {
        case MFMailComposeResultCancelled:
            NSLog(@"Result: canceled");
            break;
        case MFMailComposeResultSaved:
            NSLog(@"Result: saved");
            break;
        case MFMailComposeResultSent:
            NSLog( @"Result: sent");
            break;
        case MFMailComposeResultFailed:
            NSLog( @"Result: failed");
            break;
        default:
            NSLog( @"Result: not sent");
            break;
    }
    [self dismissModalViewControllerAnimated:YES];
}
#pragma mark - View lifecycle

- (void)initControl
{
    // Do any additional setup after loading the view from its nib.
    
    UIButton *btnBack = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 41, 46)];
    btnBack.tintColor = [UIColor blackColor];
    [btnBack setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
    [btnBack setImage:[UIImage imageNamed:kImageSetting34x46] forState:UIControlStateNormal];
    [btnBack addTarget:self action:@selector(back:) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationController.navigationBar addSubview:btnBack];
    
    
    UIButton *btnLogout = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 67, 24)];
    [btnLogout setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
	
    [btnLogout setTitle: NSLocalizedString(@"Logout", nil) forState:UIControlStateNormal];
    btnLogout.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"logout-67x24.png"]];
    btnLogout.titleLabel.font = [UIFont boldSystemFontOfSize:16.0f];
    btnLogout.titleLabel.textColor = [UIColor grayColor];
    [btnLogout addTarget:self action:@selector(logout:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btnLogout];
     [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"nav-bg-black"] forBarMetrics:UIBarMetricsDefault] ;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = NSLocalizedString(@"Settings", nil);
    
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bgback.png"]];
    self.tableViewSetting.backgroundColor = [UIColor clearColor];
    self.tableViewSetting.backgroundView = nil;
    
    self.tableViewSetting.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self initControl];
}
-(void)viewWillAppear:(BOOL)animated
{
    
    [super viewWillAppear:animated];
    [self.tableViewSetting reloadData];
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        switch (indexPath.row) {
            case 0:
                //
                break;
            case 1:
            {
				//check passcode is YES push to manage passcode,otherwise push to passcode page
                if ([CCommon checkPasscode])
                    [self pushToManagePasscode:self];
                else
                    [self pushToPasscode:self];
            }
                break;
			case 2:
				//push to change pass page
				[self pushToChangePass:self];
				break;
            case 3:
                // push to terms page
                [self pushToTerms:self];
                break;
            case 4:
                // push to privacy page
                [self pushToPrivacy:self];
                break;
            case 5:
                //check update
                break;
            case 6:
                // push to send mail support
                [self pushToMailSupport:self];
                break;
            default:
                break;
        }
    }
    else
    {
        switch (indexPath.row) {
            case 0:
                [self pushToFacebook];
                break;
            case 1:
                //
                [self pushToTwitter];
                break;
            case 2:
                //
                [self pushToMailInvite:self];
                break;
            case 3:
                //
                [self sendSMS:NSLocalizedString(@"www.kurtuluspartners.com\nModern Turkish Law Firm, I can follow my cases even from their mobile application. \nDefinitely Recommended!!!", nil) recipientList:[NSArray arrayWithObjects:@"", nil]];
                break;
            default:
                break;
        }
        //pushToMailInvite
    }
     
    [self.tableViewSetting deselectRowAtIndexPath:indexPath animated:YES];
}
- (void)viewDidUnload
{
    [self setTableViewSetting:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


- (void)publishStory
{
    
    NSMutableDictionary *postParams = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
                                       @"http://www.kurtuluspartners.com", @"link",
                                       @"Kurtulus&Partners' Services.", @"name",
                                       @"http://www.kurtuluspartners.com", @"caption",
                                       NSLocalizedString(@"www.kurtuluspartners.com\nModern Turkish Law Firm, I can follow my cases even from their mobile application. \nDefinitely Recommended!!!", nil), @"description",
                                       nil];
    
    [FBRequestConnection
     startWithGraphPath:@"me/feed"
     parameters:postParams
     HTTPMethod:@"POST"
     completionHandler:^(FBRequestConnection *connection,
                         id result,
                         NSError *error) {
         NSString *alertText;
         if (error) {
             alertText = [NSString stringWithFormat:
                          @"error: domain = %@, code = %d",
                          error.domain, error.code];
         } else {
             alertText = [NSString stringWithFormat:
                          @"Posted your invitation"];
         }
         // Show the result in an alert
         [[[UIAlertView alloc] initWithTitle:@"Result"
                                     message:alertText
                                    delegate:self
                           cancelButtonTitle:@"OK!"
                           otherButtonTitles:nil]
          show];
     }];
    //    [FBRequestConnection startForPostStatusUpdate:@"kien test" completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
    //        
    //    } ];
}

@end
